package point

import (
	"net"
)

type WanXIpPoint struct {
	index int
}

var wanxIp string

func NewWanXIpPoint() *WanXIpPoint { return &WanXIpPoint{} }

func (s *WanXIpPoint) Get() any {
	ifaces, err := net.Interfaces()
	if err != nil {
		return ""
	}

	var interfaceName string

	if s.index == 0 {
		interfaceName = "eth1"
	} else if s.index == 1 {
		interfaceName = "eth2"
	} else {
		return ""
	}

	for _, iface := range ifaces {
		if iface.Name == interfaceName {
			addrs, err := iface.Addrs()
			if err != nil {
				return ""
			}

			for _, addr := range addrs {
				ipNet, ok := addr.(*net.IPNet)
				if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
					return ipNet.IP.String()
				}
			}
		}
	}

	return ""
}

func (s *WanXIpPoint) Set(val ...any) bool {
	if len(val) < 1 {
		return false
	}

	if ip, ok := val[0].(string); ok {
		wanxIp = ip
	}

	return true
}

func (s *WanXIpPoint) SetRoute(str string) PointInterface {
	s.index = int(str[len("wan")]) - '0'
	return s
}
